package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.domain.Order;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: OrderController
 * @Author: Solomon
 * @Date: 2020/7/12 23:51
 * @Description:
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    //用户提交预约请求，处理方法
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){

        String telephone = (String) map.get("telephone");
        //校验验证码是否相同
        //从redis中获取验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");

        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //验证码校验通过，调用service方法进行预约设置
            //service中会给我们返回result对象的信息，所以我们这里不用设置
            Result result = null;
            //先设置一下预约的类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            try {
                //调用service进行预约
                result = orderService.submit(map);
            } catch (Exception e) {
                return result;
            }
            /*
            我们发送的短信为通知类型的短信，而通知类只有企业可以申请，所以我们只需要有这一步逻辑即可

            if (result.isFlag()){
                //预约成功,发送成功的短信，参数：预约日期
                try {
                    SMSUtils.sendShortMessage(SMSUtils.BOOKING_MEAL,telephone, (String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }*/
            return result;
        }else {
            //不通过
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //页面跳转到预约成功时，回显数据
    //体检人   体检套餐   体检日期   预约类型   3张表
    @RequestMapping("/findById")
    public Result findById(Integer orderId){
        try {
            Map orderMap = orderService.findById(orderId);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,orderMap);
        } catch (Exception e) {
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
